﻿Imports System.IO
Imports System.Data
Imports System.Drawing
Imports System.Web.Configuration
Imports System.Security.Cryptography
Imports System.Reflection


Public Class Utilerias

#Region "Fechas y conversiones"
    ''' <summary>
    ''' Metodo que se encarga de Validar si una fecha es mayor a la Otra
    ''' </summary>
    ''' <param name="dteMax">Fecha Maxima</param>
    ''' <param name="dteMin">Fecha Minima</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    ''' 
    Public Function validarRangoFechas(ByVal dteMax As DateTime, ByVal dteMin As DateTime) As Boolean
        If dteMax >= dteMin Then
            Return True
        Else
            Return False
        End If
    End Function


    ''' <summary>
    ''' Metodo que se encarga de Validar que las Fechas sean correctas
    ''' </summary>
    ''' <param name="strFecha">Cadena con la Fecha a Validar</param>
    ''' <returns>True si es una fecha False si no lo es</returns>
    ''' <remarks></remarks>
    Public Function validarFecha(ByVal strFecha As String) As Boolean
        'Validamos las Fechas: Fecha Minima
        Dim dteFecha As DateTime
        Try
            dteFecha = Convert.ToDateTime(strFecha)
        Catch ex As Exception
            'Mensaje de Error           
            Return False
        End Try
        Return True
    End Function

    Public Function validarFechaddMMyyyy(ByVal strFecha As String) As Boolean
        Dim bolCorreo As Boolean
        Dim espresionReg As String = "^(?:(?:0?[1-9]|1\d|2[0-8])(\/|-)(?:0?[1-9]|1[0-2]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:31(\/|-)(?:0?[13578]|1[02]))|(?:(?:29|30)(\/|-)(?:0?[1,3-9]|1[0-2])))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(29(\/|-)0?2)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$"
        Dim rgx As New RegularExpressions.Regex(espresionReg)
        If rgx.IsMatch(strFecha) Then
            bolCorreo = True
        Else
            bolCorreo = False
        End If
        Return bolCorreo
    End Function

    Public Function convertirFormatoUniversalSQLServerMMYYYYFinal(ByVal mes As String, ByVal anio As String) As String
        Dim strFechaInicial As String = String.Empty
        Dim mesCal As Integer = CType(mes, Integer)
        Dim diasMes As String = String.Empty
        If mesCal = 0 Then
            strFechaInicial = "'" & anio & "-12-31T23:59:59'"
        Else


            Select Case mesCal
                Case 1, 3, 5, 7, 8, 10, 12
                    diasMes = 31
                Case 4, 6, 9, 11
                    diasMes = 30
                Case 2
                    If (anio Mod 4 = 0) And (anio Mod 100 <> 0) Or (anio Mod 400 = 0) Then
                        diasMes = 29
                    Else
                        diasMes = 28
                    End If

            End Select
            If mesCal < 10 Then
                mes = "0" & mesCal.ToString
            End If
            strFechaInicial = "'" & anio & "-" & mes & "-" & diasMes.ToString & "T23:59:59'"
        End If


        Return strFechaInicial

    End Function

    Public Function convertirFormatoUniversalSqlServerMMYYYYInicial(ByVal mes As String, ByVal anio As String) As String
        Dim mesCal As Integer = CType(mes, Integer)
        Dim strFechaInicial As String = String.Empty
        If mesCal = 0 Then
            strFechaInicial = "'" & anio & "-01-01T00:00:00'"
        Else
            If mesCal < 10 Then
                mes = "0" & mesCal.ToString
            End If
            strFechaInicial = "'" & anio & "-" & mes & "-" & "01" & "T00:00:00'"
        End If

        Return strFechaInicial

    End Function

    Public Function convertirFormatoUniversalSqlServerYYYYInicial(ByVal anio As String) As String

        Return "'" & anio & "-01-01T00:00:00'"

    End Function

    Public Function convertirFormatoUniversalSqlServerYYYYFinal(ByVal anio As String) As String

        Return "'" & anio & "-12-31T23:59:59'"

    End Function

    ''' <summary>
    ''' Metodo que se encarga de Convertir una fecha String 
    ''' con formato dd/MM/yyyy a Date
    ''' </summary>
    ''' <param name="strFecha">String de Fecha a convertir</param>
    ''' <returns>Date</returns>
    ''' <remarks></remarks>
    Public Shared Function convertirDate(ByVal strFecha As String, ByVal intHora As Integer, ByVal intMinuto As Integer, ByVal intSegundo As Integer) As Date
        Dim fechaConvertida As Date
        Dim parts As String() = strFecha.Split("/")
        If parts.Length >= 3 Then
            fechaConvertida = New Date(CInt(parts(2)), CInt(parts(1)), CInt(parts(0)), intHora, intMinuto, intSegundo, DateTimeKind.Unspecified)
        End If

        Return fechaConvertida
    End Function

    Public Shared Function convertDateToStringSQLFormat(ByVal data As Date) As String

        Dim strDateSQLFormat As String = String.Empty

        Try

            strDateSQLFormat = Format(data, "yyyy-MM-ddTHH:mm:ss")
        Catch ex As Exception

        End Try

        Return strDateSQLFormat

    End Function

    Public Shared Function convertDateToStringddMMyyyy(ByVal data As Date) As String

        Dim strDateSQLFormat As String = String.Empty

        Try

            strDateSQLFormat = Format(data, "dd/MM/yyyy")
        Catch ex As Exception

        End Try

        Return strDateSQLFormat

    End Function

    ''' <summary>
    ''' Metodo que se encarga de convertir una fecha tipo Date a un Date con hora, minuto y segundo especifico
    ''' </summary>
    ''' <param name="dteFecha">Date de Fecha a convertir</param>
    ''' <returns>Date</returns>
    ''' <remarks></remarks>
    Public Shared Function convertirDateToDateHHMMSS(ByVal dteFecha As DateTime, ByVal intHora As Integer, ByVal intMinuto As Integer, ByVal intSegundo As Integer) As DateTime
        Dim fechaConvertida As DateTime
        fechaConvertida = New Date(dteFecha.Year, dteFecha.Month, dteFecha.Day, intHora, intMinuto, intSegundo, DateTimeKind.Unspecified)

        Return fechaConvertida
    End Function

    ''' <summary>
    ''' Metodo que se encarga de convertir una fecha tipo dd/MM/yyyy a formato Universal SQL
    ''' Para la inserción de datos.
    ''' </summary>
    ''' <param name="strFecha">Fecha Propuesta: debe de estar en formato dd/MM/yyyy</param>
    ''' <returns>String: Fecha Propuesta con formato</returns>
    ''' <remarks></remarks>
    Public Function convertirFecha_ddMMyyyyToSqlServer(ByVal strFecha As String, Optional ByVal intHora As Integer = -1, _
                                                        Optional intMinuto As Integer = -1, Optional intSegundo As Integer = -1) As String
        Dim strFechaConvertida As String = String.Empty
        Dim parts As String() = strFecha.Split(New Char() {"/"c})
        If parts.Length >= 3 Then
            If intHora = -1 And intMinuto = -1 And intSegundo = -1 Then
                strFechaConvertida = "'" & parts(2) & "-" & parts(1) & "-" & parts(0) & "T00:00:00'"
            Else
                Dim strHora As String = String.Empty
                Dim strMinuto As String = String.Empty
                Dim strSegundo As String = String.Empty
                strHora = IIf(intHora = -1, "00", IIf(CStr(intHora).Length > 1, intHora.ToString, "0" & intHora.ToString))
                strMinuto = IIf(intMinuto = -1, "00", IIf(CStr(intMinuto).Length > 1, intMinuto.ToString, "0" & intMinuto.ToString))
                strSegundo = IIf(intSegundo = -1, "00", IIf(CStr(intSegundo).Length > 1, intSegundo.ToString, "0" & intSegundo.ToString))
                strFechaConvertida = "'" & parts(2) & "-" & parts(1) & "-" & parts(0) & "T" & strHora & ":" & strMinuto & ":" & strSegundo & "'"
            End If

        End If

        Return strFechaConvertida
    End Function

    ''' <summary>
    ''' Metodo que se encarga de calcular los sabados y domingos 
    ''' entre un rango de fechas.
    ''' </summary>
    ''' <param name="fechaInicial">Fecha Inicial: fecha inicial</param>
    ''' <param name="fechaFinal">Fecha Final: fecha final</param>
    ''' <returns>Integer: dias sabado y domingos</returns>
    ''' <remarks>/remarks>
    Public Function diasSabado_Y_Domingo(ByVal fechaInicial As Date, ByVal fechaFinal As Date) As Integer

        Dim intDays As Integer = 0
        Dim intSabado_Domingo As Integer = 0
        Dim diff As TimeSpan = fechaFinal - fechaInicial
        intDays = diff.Days
        For i As Integer = 0 To intDays Step 1
            Dim testDate As Date = fechaInicial.AddDays(i)
            Select Case testDate.DayOfWeek
                Case DayOfWeek.Saturday
                    intSabado_Domingo += 1
                Case DayOfWeek.Sunday
                    intSabado_Domingo += 1
            End Select
        Next

        Return intSabado_Domingo

    End Function

    ''' <summary>
    ''' Metodo que se encarga de calcular los días hábiles entre un par de fechas 
    ''' </summary>
    ''' <param name="fechaInicial">Fecha Inicial: fecha inicial</param>
    ''' <param name="fechaFinal">Fecha Final: fecha final</param>
    ''' <returns>Integer: días hábiles</returns>
    ''' <remarks>/remarks>
    Public Shared Function calcularDiasHabiles(ByVal fechaInicial As Date, ByVal fechaFinal As Date) As Integer

        Dim intDays As Integer = 0
        Dim intSabado_Domingo As Integer = 0
        Dim diff As TimeSpan = fechaFinal - fechaInicial
        intDays = diff.Days
        For i As Integer = 0 To intDays Step 1
            Dim testDate As Date = fechaInicial.AddDays(i)
            Select Case testDate.DayOfWeek
                Case DayOfWeek.Saturday
                    intSabado_Domingo += 1
                Case DayOfWeek.Sunday
                    intSabado_Domingo += 1
            End Select
        Next

        Return intDays - intSabado_Domingo

    End Function

    ''' <summary>
    ''' Metodo que se encarga de calcular el total de días hábiles que existen en el mes
    ''' </summary>
    ''' <param name="fechaInicial">FechaCalcularDiasHabilesMes: fecha para calcular el total de dias hábiles en el mes</param>
    ''' <returns>Integer: días hábiles</returns>
    ''' <remarks>/remarks>
    Public Shared Function calcularDiasHabilesMes(ByVal fechaCalcularDiasHabilesMes As Date) As Integer

        Dim intDays As Integer = 0
        Dim intSabado_Domingo As Integer = 0
        intDays = DateTime.DaysInMonth(fechaCalcularDiasHabilesMes.Year, fechaCalcularDiasHabilesMes.Month)
        Dim fechaDiasMes As Date = New DateTime(fechaCalcularDiasHabilesMes.Year, fechaCalcularDiasHabilesMes.Month, 1)
        For i As Integer = 0 To intDays Step 1
            Dim testDate As Date = fechaDiasMes.AddDays(i)
            Select Case testDate.DayOfWeek
                Case DayOfWeek.Saturday
                    intSabado_Domingo += 1
                Case DayOfWeek.Sunday
                    intSabado_Domingo += 1
            End Select
        Next

        Return intDays - intSabado_Domingo

    End Function

    ''' <summary>
    ''' Metodo que se encarga de calcular el total de días hábiles que existen en el año
    ''' </summary>
    ''' <param name="fechaInicial">FechaCalcularDiasHabilesMes: fecha para calcular el total de dias hábiles en el año</param>
    ''' <returns>Integer: días hábiles</returns>
    ''' <remarks>/remarks>
    Public Shared Function calcularDiasHabilesAnio(ByVal fechaCalcularDiasHabilesAnio As Date) As Integer

        Dim intDays As Integer = 0
        Dim intSabado_Domingo As Integer = 0
        intDays = IIf(DateTime.IsLeapYear(fechaCalcularDiasHabilesAnio.Year) = True, 365, 366)
        Dim fechaDiasAnio As Date = New DateTime(fechaCalcularDiasHabilesAnio.Year, 1, 1)
        For i As Integer = 0 To intDays Step 1
            Dim testDate As Date = fechaDiasAnio.AddDays(i)
            Select Case testDate.DayOfWeek
                Case DayOfWeek.Saturday
                    intSabado_Domingo += 1
                Case DayOfWeek.Sunday
                    intSabado_Domingo += 1
            End Select
        Next

        Return intDays - intSabado_Domingo

    End Function

    ''' <summary>
    ''' Metodo que se encarga de calcular los días hábiles entre un par de fechas basado en la fecha de inicio con la fecha final
    ''' </summary>
    ''' <param name="fechaInicial">Fecha Inicial: fecha inicial</param>
    ''' <param name="fechaFinal">Fecha Final: fecha final</param>
    ''' <returns>Integer: días hábiles</returns>
    ''' <remarks>/remarks>
    Public Shared Function calcularDiasHabilesPeriodo(ByVal fechaInicial As Date, ByVal fechaFinal As Date, ByVal periodo As DateInterval) As Integer

        Dim intDays As Integer = 0
        Dim intDiasPeriodo As Integer = 0
        Dim minStartPeriodo As Date = Nothing
        Dim maxFinishPeriodo As Date = Nothing

        If periodo = DateInterval.Weekday Then
            minStartPeriodo = calcularDiaEntreSemana(fechaInicial, DayOfWeek.Monday)
            maxFinishPeriodo = calcularDiaEntreSemana(fechaInicial, DayOfWeek.Sunday)
        ElseIf periodo = DateInterval.Month Then
            minStartPeriodo = PrimerDiaDelMesDesdeDateTime(fechaInicial)
            maxFinishPeriodo = UltimoDiaDelMesDesdeDateTime(fechaInicial)
        ElseIf periodo = DateInterval.Year Then
            minStartPeriodo = PrimerDiaDelAnioDesdeDateTime(fechaInicial)
            maxFinishPeriodo = UltimoDiaDelAnioDesdeDateTime(fechaInicial)
        Else
            Return -1
        End If
        Dim diff As TimeSpan = maxFinishPeriodo - minStartPeriodo
        intDays = diff.Days
        For i As Integer = 0 To intDays Step 1
            Dim testDate As Date
            If i = 0 Then
                testDate = minStartPeriodo
            Else
                testDate = minStartPeriodo.AddDays(i)
            End If

            Select Case testDate.DayOfWeek
                Case DayOfWeek.Saturday
                Case DayOfWeek.Sunday
                    intDiasPeriodo += 0
                Case Else
                    If Date.Compare(testDate, fechaInicial) >= 0 And Date.Compare(fechaFinal, testDate) >= 0 Then
                        intDiasPeriodo += 1
                    End If
            End Select
        Next

        Return intDiasPeriodo

    End Function

    Public Shared Function calcularDiaEntreSemana(ByVal dt As DateTime, ByVal diaInicio As DayOfWeek) As DateTime
        Dim diff As Integer = 0
        Dim fechaRes As DateTime = Nothing
        If diaInicio <> DayOfWeek.Sunday Then
            diff = dt.DayOfWeek - diaInicio
            If diff < 0 Then
                diff += 7
            End If
            fechaRes = dt.AddDays(-1 * diff)
        Else
            Select Case dt.DayOfWeek
                Case DayOfWeek.Monday
                    diff += 6
                Case DayOfWeek.Tuesday
                    diff += 5
                Case DayOfWeek.Wednesday
                    diff += 4
                Case DayOfWeek.Thursday
                    diff += 3
                Case DayOfWeek.Friday
                    diff += 2
                Case DayOfWeek.Saturday
                    diff += 1
            End Select

            fechaRes = dt.AddDays(diff)
        End If

        Return fechaRes
    End Function

    Public Shared Function PrimerDiaDelMesDesdeDateTime(dateTime As DateTime) As DateTime
        Return New DateTime(dateTime.Year, dateTime.Month, 1)
    End Function

    Public Shared Function UltimoDiaDelMesDesdeDateTime(dateTime As DateTime) As DateTime
        Dim firstDayOfTheMonth As New DateTime(dateTime.Year, dateTime.Month, 1)
        Return firstDayOfTheMonth.AddMonths(1).AddDays(-1)
    End Function

    Public Shared Function PrimerDiaDelAnioDesdeDateTime(dateTime As DateTime) As DateTime
        Return New DateTime(dateTime.Year, 1, 1)
    End Function

    Public Shared Function UltimoDiaDelAnioDesdeDateTime(dateTime As DateTime) As DateTime
        Dim firstDayOfTheMonth As New DateTime(dateTime.Year, 12, 1)
        Return firstDayOfTheMonth.AddMonths(1).AddDays(-1)
    End Function

    'Public Shared Function calcularDiaEntreMes(ByVal dt As DateTime, ByVal diaInicio As DayOfWeek) As DateTime

    '    Dim fechaRes As DateTime = Nothing
    '    Dim fechaConvertida As DateTime
    '    fechaConvertida = New Date(dt.Year, dt.Month, 1, dt.Hour, dt.Minute, dt.Second, DateTimeKind.Unspecified)
    '    fechaConvertida.AddDays(-7)
    '    Do While fechaConvertida.DayOfWeek <> diaInicio
    '        fechaConvertida = fechaConvertida.AddDays(1)
    '    Loop
    '    'Select Case dt.DayOfWeek
    '    '    Case diaInicio
    '    'Do While dt.DayOfWeek <> diaInicio
    '    '    fechaRes = dt.AddDays(1)
    '    'Loop
    '    'Case DayOfWeek.Tuesday
    '    '    Do While dt.DayOfWeek <> DayOfWeek.Tuesday
    '    '        fechaRes = dt.AddDays(1)
    '    '    Loop
    '    'Case DayOfWeek.Wednesday
    '    '    Do While dt.DayOfWeek <> DayOfWeek.Wednesday
    '    '        fechaRes = dt.AddDays(1)
    '    '    Loop
    '    'Case DayOfWeek.Thursday
    '    '    Do While dt.DayOfWeek <> DayOfWeek.Thursday
    '    '        fechaRes = dt.AddDays(1)
    '    '    Loop
    '    'Case DayOfWeek.Friday
    '    '    Do While dt.DayOfWeek <> DayOfWeek.Friday
    '    '        fechaRes = dt.AddDays(1)
    '    '    Loop
    '    'Case DayOfWeek.Saturday
    '    '    Do While dt.DayOfWeek <> DayOfWeek.Saturday
    '    '        fechaRes = dt.AddDays(1)
    '    '    Loop
    '    'Case DayOfWeek.Sunday
    '    '    Do While dt.DayOfWeek <> DayOfWeek.Sunday
    '    '        fechaRes = dt.AddDays(1)
    '    '    Loop
    '    'End Select


    '    Return fechaConvertida
    'End Function


 
    Public Shared Function CalcularDiferenciaEntreMeses(ByVal fechaInicial As DateTime, ByVal fechaFinal As DateTime) As Integer
        If fechaInicial > fechaFinal Then
            ' If from > to, invert
            Dim temp = fechaInicial
            fechaInicial = fechaFinal
            fechaFinal = temp
        End If

        Dim monthDiff = Math.Abs((fechaFinal.Year * 12 + (fechaFinal.Month - 1)) - (fechaInicial.Year * 12 + (fechaInicial.Month - 1)))

        If fechaInicial.AddMonths(monthDiff) > fechaFinal OrElse fechaFinal.Day < fechaInicial.Day Then
            Return monthDiff - 1
        Else
            Return monthDiff
        End If
    End Function


    Public Shared Function CalcularDiferenciaEntreAnios(ByVal fechaInicial As DateTime, ByVal fechaFinal As DateTime) As Integer
        Dim diff As TimeSpan = fechaFinal - fechaInicial

        Return (diff.TotalDays / 365.25)
    End Function

    ''' <summary>
    ''' Metodo que se encarga de convertir un tipo dataset en una lista de Row    ''' </summary>
    ''' <param name="ds">DataSet a convertir</param>
    ''' <returns>List DataRow</returns>
    ''' <remarks></remarks>
    Public Shared Function convertirDatasetToListDatarow(ByVal ds As Data.DataSet) As List(Of DataRow)
        Dim drlist As New List(Of DataRow)()

        If Not ds Is Nothing Then
            If ds.Tables.Count > 0 Then
                If ds.Tables(0).Rows.Count > 0 Then
                    For Each row As DataRow In ds.Tables(0).Rows
                        drlist.Add(CType(row, DataRow))
                    Next row
                End If
            End If
        End If

        Return drlist
    End Function

  


#End Region

#Region "Criptografia"

    Public Shared Function encriptarCadenaBase64(ByVal strCadena As String) As String

        Return Convert.ToBase64String(New System.Text.ASCIIEncoding().GetBytes(strCadena))

    End Function

    Public Shared Function desencriptarCadenaBase64(ByVal strCadenaEncriptada As String) As String

        Return New System.Text.ASCIIEncoding().GetString(Convert.FromBase64String(strCadenaEncriptada))

    End Function


    'Funcion para el Encriptado de Cadenas de Texto
    Public Shared Function Encriptar(ByVal texto As String) As String
        Dim des As New TripleDESCryptoServiceProvider 'Algorithmo TripleDES
        Dim hashmd5 As New MD5CryptoServiceProvider 'objeto md5
        Dim myKey As String = "MyKey2012" 'Clave secreta(puede alterarse)

        If Trim(texto) = "" Then
            Encriptar = ""
        Else
            des.Key = hashmd5.ComputeHash((New UnicodeEncoding).GetBytes(myKey))
            des.Mode = CipherMode.ECB
            Dim encrypt As ICryptoTransform = des.CreateEncryptor()
            Dim buff() As Byte = UnicodeEncoding.ASCII.GetBytes(texto)
            Encriptar = Convert.ToBase64String(encrypt.TransformFinalBlock(buff, 0, buff.Length))
        End If
        Return Encriptar
    End Function


    'Funcion para el Desencriptado de Cadenas de Texto
    Public Shared Function Desencriptar(ByVal texto As String) As String
        Dim des As New TripleDESCryptoServiceProvider 'Algorithmo TripleDES
        Dim hashmd5 As New MD5CryptoServiceProvider 'objeto md5
        Dim myKey As String = "MyKey2012" 'Clave secreta(puede alterarse)

        If Trim(texto) = "" Then
            Desencriptar = ""
        Else
            des.Key = hashmd5.ComputeHash((New UnicodeEncoding).GetBytes(myKey))
            des.Mode = CipherMode.ECB
            Dim desencrypta As ICryptoTransform = des.CreateDecryptor()
            Dim buff() As Byte = Convert.FromBase64String(texto)
            Desencriptar = UnicodeEncoding.ASCII.GetString(desencrypta.TransformFinalBlock(buff, 0, buff.Length))
        End If
        Return Desencriptar
    End Function

#End Region

#Region "Controles y ASP.NET"
    ''' <summary>
    ''' Metodo que se encarga de colocar en la posición 0 los dropandlist
    ''' </summary>
    ''' <param name="drpControl"></param>
    ''' <remarks></remarks>

    Public Sub limpiarDropDrown(ByRef drpControl As DropDownList)
        For Each item As ListItem In drpControl.Items
            item.Selected = 0
        Next
    End Sub



    Public Shared Sub BindDropDownList(ByRef ddlControl As DropDownList, ByVal dataSource As IEnumerable(Of Object), ByVal strTextField As String, ByVal strValueField As String, Optional ByVal strExtraNameTextItem As String = Nothing, Optional ByVal strExtraValueTextItem As String = Nothing)
        Try
            ddlControl.DataSource = dataSource
            ddlControl.DataTextField = strTextField
            ddlControl.DataValueField = strValueField
            ddlControl.DataBind()


            If Not strExtraNameTextItem Is Nothing And Not strExtraValueTextItem Is Nothing Then
                ddlControl.Items.Remove("")
                Dim listItem As New ListItem
                listItem.Text = strExtraNameTextItem
                listItem.Value = strExtraValueTextItem
                ddlControl.Items.Insert(0, listItem)
            End If

        Catch ex As Exception

        End Try

    End Sub
         

    ''' <summary>
    ''' Muestra los Mensajes de Error de la Pagina
    ''' </summary>
    ''' <param name="strMensaje">Mensaje a Desplegar</param>
    ''' <remarks></remarks>
    Public Sub MensajeError(ByVal strMensaje As String, ByRef frmPagina As Page)
        Dim ctrlLiteral As New LiteralControl
        Try
            strMensaje = strMensaje.Replace("'", " ")
            strMensaje = strMensaje.Replace(";", " ")
            strMensaje = strMensaje.Replace("""", " ")
            frmPagina.Response.Write("<script language=javascript type=text/javascript>")
            frmPagina.Response.Write("alert(""" & strMensaje & """);")
            frmPagina.Response.Write("</script>")
            frmPagina.Controls.Add(ctrlLiteral)
        Catch ex As Exception

        End Try
    End Sub


    ''' <summary>
    ''' Obtiene la direccion URL con la referencia que se le envia
    ''' </summary>
    ''' <param name="file">Ruta a la pagina local donde queremos ir</param>
    ''' <returns>Direccion completa con la pagina  a la que queremos entrar</returns>
    ''' <remarks></remarks>
    Public Function generarPathRaiz(ByVal file As String, ByRef Request As System.Web.HttpRequest) As String
        Dim strPath As String = Request.ApplicationPath
        Return String.Format("http://{0}{1}/{2}", Request.Url.Authority, strPath, file)
    End Function

    ''' <summary>
    ''' Obtiene la direccion URL con la referencia que se le envia
    ''' </summary>
    ''' <param name="file">Ruta a la pagina local donde queremos ir</param>
    ''' <returns>Direccion completa con la pagina  a la que queremos entrar</returns>
    ''' <remarks></remarks>
    Public Function generarPathInventario(ByVal file As String, ByRef Request As System.Web.HttpRequest) As String
        Dim strPath As String = Request.ApplicationPath
        Return String.Format("http://{0}{1}/Inventario/{2}", Request.Url.Authority, strPath, file)
    End Function

    Public Function GenerarNuevoPath(ByVal nvaAplicacion As String, ByRef Request As System.Web.HttpRequest) As String
        Dim ruta As String
        Try
            ruta = (String.Format("http://{0}/{1}", Request.Url.Authority, nvaAplicacion))
        Catch ex As Exception
            ruta = ""
        End Try
        Return ruta
    End Function

    ''' <summary>
    ''' Metodo que se encarga de regresar una  cadena con formato de Java Script
    ''' </summary>
    ''' <param name="strScript">Comando JavaSript</param>
    ''' <returns>Cadena lista para agregarse como codigo embedido</returns>
    ''' <remarks></remarks>

    Public Function agregarComandoJavaScript(ByVal strScript As String) As String
        Dim strCodigo As String = String.Empty
        strCodigo = "<script type=""text/javascript"">" + strScript + "</script>"
        Return strCodigo
    End Function

    ''' <summary>
    ''' Metodo que se encarga de agregar un valor nulo  a los Drop Drown List
    ''' </summary>
    ''' <param name="drpObjeto"> Drop Drown al que se le agregara el valor nulo</param>
    ''' <remarks></remarks>
    Public Sub agregarValorNull(ByRef drpObjeto As DropDownList)
        drpObjeto.DataBind()
        drpObjeto.Items.Insert(0, New ListItem("-", "NULL"))
    End Sub

    ''' <summary>
    ''' Metodo que se encarga de convertir un gridview en un word. 
    ''' </summary>
    ''' <param name="nombreArchivo">String nombre de archivo saliente</param>
    ''' <param name="grdResultados">GridView el cual se importara</param>
    ''' <param name="Pagina">Pagina nombre de la página saliente</param>
    ''' <returns>Void</returns>
    ''' <remarks></remarks>
    Public Shared Sub GridviewAWord(ByVal nombreArchivo As String, ByVal grdResultados As GridView, ByRef Pagina As System.Web.UI.Page)

        Dim sb As StringBuilder = New StringBuilder()
        Dim sw As StringWriter = New StringWriter(sb)
        Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
        Dim pagina1 As New System.Web.UI.Page
        Dim form = New HtmlForm

        grdResultados.EnableViewState = False
        grdResultados.AllowPaging = False
        pagina1.EnableEventValidation = False
        pagina1.DesignerInitialize()
        pagina1.Controls.Add(form)
        form.Controls.Add(grdResultados)
        pagina1.RenderControl(htw)
        Pagina.Response.Clear()
        Pagina.Response.Buffer = True
        Pagina.Response.ContentType = "application/vnd.word"
        Pagina.Response.AddHeader("Content-Disposition", "attachment;filename=FileName.doc")
        Pagina.Response.Charset = "UTF-8"
        Pagina.Response.ContentEncoding = Encoding.Default
        Pagina.Response.Write(sb.ToString())
        Pagina.Response.End()
    End Sub

    ''' <summary>
    ''' Metodo que se encarga de convertir un gridview en un excel. 
    ''' </summary>
    ''' <param name="nombreArchivo">String nombre de archivo saliente</param>
    ''' <param name="grdResultados">GridView el cual se importara</param>
    ''' <param name="Pagina">Pagina nombre de la página saliente</param>
    ''' <returns>Void</returns>
    ''' <remarks></remarks>
    Public Shared Sub GridviewAExcel(ByVal nombreArchivo As String, ByVal grdResultados As GridView, ByRef miPagina As System.Web.UI.Page)
        miPagina.Response.ContentType = "application/vnd.ms-excel"
        miPagina.Response.AddHeader("Content-Disposition", "attachment;filename=" & nombreArchivo & ".xls")
        miPagina.Response.Charset = "UTF-8"
        miPagina.Response.ContentEncoding = Encoding.Default

        Dim sb As StringBuilder = New StringBuilder()
        Dim sw As StringWriter = New StringWriter(sb)
        Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
        Dim pagina As Page = New Page
        Dim form = New HtmlForm
        grdResultados.EnableViewState = False
        grdResultados.AllowPaging = False
        pagina.EnableEventValidation = False
        pagina.DesignerInitialize()
        pagina.Controls.Add(form)
        form.Controls.Add(grdResultados)
        pagina.RenderControl(htw)
        miPagina.Response.Clear()
        miPagina.Response.Buffer = True

        miPagina.Response.Write(sb.ToString())
        miPagina.Response.End()
    End Sub


    ' ''' <summary>
    ' ''' Metodo que se encarga de convertir un gridview en un pdf. 
    ' ''' </summary>
    ' ''' <param name="nombreArchivo">String nombre de archivo saliente</param>
    ' ''' <param name="grdResultados">GridView el cual se importara</param>
    ' ''' <param name="Pagina">Pagina nombre de la página saliente</param>
    ' ''' <returns>Void</returns>
    ' ''' <remarks></remarks>
    'Public Shared Sub GridviewAPDF(ByVal nombreArchivo As String, ByVal grdResultados As GridView, ByRef miPagina As System.Web.UI.Page)
    '    miPagina.Response.Clear()

    '    grdResultados.AllowPaging = False
    '    grdResultados.DataBind()

    '    'Create a table
    '    Dim table As New iTextSharp.text.pdf.PdfPTable(grdResultados.Columns.Count)
    '    'table. = 5

    '    'Set the column widths
    '    Dim widths As Integer() = New Integer(grdResultados.Columns.Count - 1) {}
    '    For x As Integer = 0 To grdResultados.Columns.Count - 1
    '        widths(x) = CInt(grdResultados.Columns(x).ItemStyle.Width.Value)
    '        Dim cellText As String = _
    '           System.Web.HttpContext.Current.Server.HtmlDecode(grdResultados.HeaderRow.Cells(x).Text)
    '        Dim cell As New iTextSharp.text.pdf.PdfPCell(New iTextSharp.text.Phrase(cellText))
    '        cell.Colspan = 2
    '        cell.Border = 0
    '        cell.HorizontalAlignment = 1
    '        cell.BackgroundColor = iTextSharp.text.BaseColor.GRAY
    '        table.AddCell(cell)
    '    Next
    '    table.SetWidths(widths)

    '    'Transfer rows from GridView to table
    '    For i As Integer = 0 To grdResultados.Rows.Count - 1
    '        If grdResultados.Rows(i).RowType = DataControlRowType.DataRow Then
    '            For j As Integer = 0 To grdResultados.Columns.Count - 1
    '                Dim cellText As String = _
    '                   System.Web.HttpContext.Current.Server.HtmlDecode(grdResultados.Rows(i).Cells(j).Text)
    '                Dim cell As New iTextSharp.text.pdf.PdfPCell(New iTextSharp.text.Phrase(cellText))
    '                cell.Colspan = 2
    '                cell.Border = 0
    '                cell.HorizontalAlignment = 1

    '                'Set Color of Alternating row
    '                If i Mod 2 <> 0 Then
    '                    cell.BackgroundColor = New iTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#C2D69B"))
    '                    'New Color(System.Drawing.ColorTranslator.FromHtml("#C2D69B"))
    '                Else
    '                    cell.BackgroundColor = iTextSharp.text.BaseColor.WHITE
    '                End If
    '                table.AddCell(cell)
    '            Next
    '        End If
    '    Next
    '    'Create the PDF Document
    '    Dim pdfDoc As New iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
    '    PdfWriter.GetInstance(pdfDoc, miPagina.Response.OutputStream)
    '    pdfDoc.Open()
    '    pdfDoc.Add(table)
    '    pdfDoc.Close()
    '    miPagina.Response.ContentType = "application/pdf"
    '    miPagina.Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
    '    miPagina.Response.Cache.SetCacheability(HttpCacheability.NoCache)
    '    miPagina.Response.Write(pdfDoc)
    '    miPagina.Response.End()



    ''miPagina.Response.ContentType = "application/pdf"
    ''miPagina.Response.AddHeader("content-disposition", "attachment;filename=" & nombreArchivo & ".pdf")
    ''miPagina.Response.Charset = "UTF-8"
    ''miPagina.Response.Cache.SetCacheability(HttpCacheability.NoCache)

    ''Dim form = New HtmlForm
    ''Dim pagina As New Page
    ''pagina.EnableEventValidation = False
    ''pagina.DesignerInitialize()
    ''pagina.Controls.Add(form)


    ' ''pagina.RenderControl(htw)

    ''Dim sw As New StringWriter()
    ''Dim hw As New HtmlTextWriter(sw)
    ''grdResultados.AllowPaging = False
    ''grdResultados.DataBind()

    ''form.Controls.Add(grdResultados)
    ''pagina.RenderControl(hw)
    ' ''grdResultados.RenderControl(hw)

    ''Dim sr As New StringReader(sw.ToString())
    ''Dim pdfDoc As New iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
    ''Dim htmlparser As New iTextSharp.text.html.simpleparser.HTMLWorker(pdfDoc)
    ''iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, miPagina.Response.OutputStream)
    ''pdfDoc.Open()
    ''htmlparser.Parse(sr)
    ''pdfDoc.Close()
    ''miPagina.Response.Write(pdfDoc)
    ''miPagina.Response.End()
    ' End Sub




#End Region

#Region "Validaciones Expresiones Regulares"

    Public Shared Function validarComillas(ByVal strCadenaComillas As String) As String
        If strCadenaComillas.Contains(New Char() {"'"c}) Then

            strCadenaComillas = strCadenaComillas.Replace(New Char() {"'"c}, "''")

        End If
        Return strCadenaComillas
    End Function

    Public Shared Function CapitalLetra(source As String) As String
        If String.IsNullOrEmpty(source) Then
            Return String.Empty
        End If
        ' convert to char array of the string
        Dim letters As Char() = source.ToCharArray()
        ' upper case the first char
        letters(0) = Char.ToUpper(letters(0))
        ' return the array made of the new char array
        Return New String(letters)
    End Function

    Public Function validarCorreo(ByVal strCorreo As String) As Boolean
        Dim bolCorreo As Boolean
        Dim rgx As New RegularExpressions.Regex("\w+([-+.´]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")
        If rgx.IsMatch(strCorreo) Then
            bolCorreo = True
        Else
            bolCorreo = False
        End If
        Return bolCorreo
    End Function



    ''' <summary>
    ''' Metodo que se encarga de obtener el porcentaje de una cifra
    ''' </summary>
    ''' <param name="dividendo">Dividendo</param>
    ''' <param name="divisor">Divisor</param>
    ''' <returns>Double</returns>
    ''' <remarks></remarks>
    Public Shared Function Dividir(ByVal dividendo As Double, ByVal divisor As Double) As Double
        If divisor = 0.0 Then
            Return 0.0
        End If
        Return (dividendo / divisor)
    End Function


    ''' <summary>
    ''' Metodo que se encarga de obtener el porcentaje en formato string, 
    ''' si el valor de decimal se omite, las decimales las regresa dependiendo la region
    ''' </summary>
    ''' <param name="strFecha">String de Fecha a convertir</param>
    ''' <returns>Date</returns>
    ''' <remarks></remarks>
    Public Shared Function PorcentajeCadena(ByVal CurrVal As Double, ByVal MaxVal As Double, Optional ByVal intNumDecimales As Integer = -1) As String
        Dim strValor As String = String.Empty
        If MaxVal = 0.0 Then
            strValor = "0%"
            Return strValor
        ElseIf CurrVal = 0.0 Then
            strValor = "0%"
            Return strValor
        End If
        If intNumDecimales = -1 Then
            Return FormatPercent((CurrVal / MaxVal))
        Else
            Return FormatPercent((CurrVal / MaxVal), intNumDecimales, TriState.False)
        End If
        Return strValor
    End Function

    Public Shared Function QuitarTagsHtml(html As String) As String
        If html Is Nothing OrElse html = String.Empty Then
            Return String.Empty
        End If
        Return System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", String.Empty)
    End Function

#End Region

#Region "Archivos IO"

    Public Function moverArchivoTemporalAFolio(ByVal strFolio As String, ByVal strNombreCarpetaTemporal As String) As Boolean
        Dim strPath As String = System.Configuration.ConfigurationManager.AppSettings("AttachedFilesPath")
        Dim strCurrDirectory As String
        Dim strNombreArchivo As String = String.Empty
        Dim rutaInicial As String = String.Empty
        Dim rutaFinal As String = String.Empty
        Dim root As String = String.Empty
        Dim strTemporales As String = "Temporales"
        Dim strPerfil As String = "Lider"
        Dim strNombreSubcarpeta As String = "DocRequerimiento"
        Dim bolRes As Boolean = False

        ' Esta rutina crea un directorio con el numero de folio en turno
        If Directory.Exists(strPath & strFolio) = False Then
            ChDir(strPath)
            Directory.CreateDirectory(strFolio)
            ChDir(strFolio)
            Directory.SetCurrentDirectory(strPath & strFolio)
            strCurrDirectory = Directory.GetCurrentDirectory.ToString
            ' Esta rutina crea un directorio con el perfil y el directorio antes creado 
            If Directory.Exists(strPath & strFolio & "\" & strPerfil) = False Then
                ChDir(strPath)
                Directory.CreateDirectory(strFolio & "\" & strPerfil)
                ChDir(strFolio & "\" & strPerfil)
                Directory.SetCurrentDirectory(strPath & strFolio & "\" & strPerfil)
                strCurrDirectory = Directory.GetCurrentDirectory.ToString
                If Directory.Exists(strPath & strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta) = False Then
                    ChDir(strPath)
                    Directory.CreateDirectory(strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta)
                    ChDir(strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta)
                    Directory.SetCurrentDirectory(strPath & strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta)
                    strCurrDirectory = Directory.GetCurrentDirectory.ToString
                End If
            End If
        ElseIf Directory.Exists(strPath & strFolio & "\" & strPerfil) = False Then
            ChDir(strPath)
            Directory.CreateDirectory(strFolio & "\" & strPerfil)
            ChDir(strFolio & "\" & strPerfil)
            Directory.SetCurrentDirectory(strPath & strFolio & "\" & strPerfil)
            strCurrDirectory = Directory.GetCurrentDirectory.ToString
            If Directory.Exists(strPath & strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta) = False Then
                ChDir(strPath)
                Directory.CreateDirectory(strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta)
                ChDir(strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta)
                Directory.SetCurrentDirectory(strPath & strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta)
                strCurrDirectory = Directory.GetCurrentDirectory.ToString
            End If
        Else
            If Directory.Exists(strPath & strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta) = False Then
                ChDir(strPath)
                Directory.CreateDirectory(strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta)
                ChDir(strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta)
                Directory.SetCurrentDirectory(strPath & strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta)
                strCurrDirectory = Directory.GetCurrentDirectory.ToString
            End If
        End If

        root = System.Configuration.ConfigurationManager.AppSettings("AttachedFilesPath") & "Temporales" & "\" & strNombreCarpetaTemporal & "\"
        If Directory.Exists(root) = True Then
            Dim directoryInfo As New DirectoryInfo(root)

            For Each fileInfo In directoryInfo.GetFiles("*.*")
                strNombreArchivo = fileInfo.Name.Trim
            Next

            If strNombreArchivo.Trim.Length > 0 Then
                rutaInicial = strPath & "Temporales" & "\" & strNombreCarpetaTemporal & "\"
                rutaFinal = strPath & strFolio & "\" & strPerfil & "\" & strNombreSubcarpeta & "\"
                MoveFiles(rutaInicial, rutaFinal)
                Directory.Delete(root)
                bolRes = True
            End If
        End If

        Return bolRes
    End Function

    Public Shared Sub MoveFiles(ByVal sourcePath As String, ByVal DestinationPath As String)
        If (Directory.Exists(sourcePath)) Then
            For Each fName As String In Directory.GetFiles(sourcePath)
                If File.Exists(fName) Then
                    Dim dFile As String = String.Empty
                    dFile = Path.GetFileName(fName)
                    Dim dFilePath As String = String.Empty
                    dFilePath = DestinationPath + dFile
                    File.Move(fName, dFilePath)
                End If
            Next
        End If
    End Sub

    Public Shared Sub DeleteFiles(ByVal sourcePath As String, Optional ByVal strExtencion As String = "")
        If (Directory.Exists(sourcePath)) Then
            For Each fName As String In Directory.GetFiles(sourcePath)
                If File.Exists(fName) Then
                    If strExtencion.Trim.Length > 0 Then
                        If strExtencion.Trim.ToLower.Equals(Path.GetExtension(fName).Trim.ToLower) = True Then
                            Dim dFilePath As String = String.Empty
                            dFilePath = sourcePath + IO.Path.DirectorySeparatorChar & Path.GetFileName(fName)
                            File.Delete(dFilePath)
                        End If
                    Else
                        Dim dFilePath As String = String.Empty
                        dFilePath = sourcePath + IO.Path.DirectorySeparatorChar & Path.GetFileName(fName)
                        File.Delete(dFilePath)
                    End If
                End If
            Next
        End If
    End Sub

    Public Shared Function rutaCompletaArchivo(ByVal sourcePath As String, Optional ByVal strExtencion As String = "") As String
        Dim strRutaCompleta As String = String.Empty

        If (Directory.Exists(sourcePath)) Then
            For Each fName As String In Directory.GetFiles(sourcePath)
                If File.Exists(fName) Then
                    If strExtencion.Trim.Length > 0 Then
                        If strExtencion.Trim.ToLower.Equals(Path.GetExtension(fName).Trim.ToLower) = True Then
                            Dim dFile As String = String.Empty
                            dFile = Path.GetFileName(fName)
                            strRutaCompleta = sourcePath + dFile
                        End If
                    Else

                        Dim dFile As String = String.Empty
                        dFile = Path.GetFileName(fName)
                        strRutaCompleta = sourcePath + dFile
                    End If
                End If
            Next
        End If

        Return strRutaCompleta
    End Function

    Public Shared Function verificarExistenciaArchivo(ByVal sourcePath As String, Optional ByVal strExtencion As String = "") As Boolean

        Dim bolRes As Boolean = False
        If (Directory.Exists(sourcePath)) Then
            For Each fName As String In Directory.GetFiles(sourcePath)
                If File.Exists(fName) Then
                    If strExtencion.Trim.Length > 0 Then
                        If strExtencion.Trim.ToLower.Equals(Path.GetExtension(fName).Trim.ToLower) = True Then
                            bolRes = True
                        End If
                    Else
                        bolRes = True
                    End If
                End If
            Next
        End If
        Return bolRes
    End Function

    Public Shared Function obtenerNombreArchivo(ByVal sourcePath As String, ByVal strExtencion As String) As String
        Dim strRutaCompleta As String = String.Empty
        Dim dFile As String = String.Empty
        If (Directory.Exists(sourcePath)) Then

            For Each fName As String In Directory.GetFiles(sourcePath)
                If File.Exists(fName) Then
                    If strExtencion.Trim.Length > 0 Then
                        If strExtencion.Trim.ToLower.Equals(Path.GetExtension(fName).Trim.ToLower) = True Then
                            dFile = Path.GetFileName(fName)
                        End If
                    End If


                End If
            Next

        End If
        Return dFile
    End Function

    Public Function GetFileCount(ByVal strPath As String) As Integer
        Dim intValor As Integer = 0
        Try
            intValor = System.IO.Directory.GetFiles(strPath, "*.*", IO.SearchOption.AllDirectories).Length()
        Catch ex As Exception

        End Try
        Return intValor
    End Function

    Public Function obtenerArchivosPorDesarrollador(ByVal strFolio As String) As Integer
        Dim intNumArchivos As Integer = 0
        Dim strPath As String = String.Empty
        strPath = System.Configuration.ConfigurationManager.AppSettings("AttachedFilesPath")
        strPath &= strFolio & "/Desarrolladores/"
        intNumArchivos = GetFileCount(strPath)
        Return intNumArchivos
    End Function


    Public Shared Function obtenerNombreArchivoJPG(ByVal sourcePath As String) As Hashtable
        Dim strRutaCompleta As String = String.Empty
        Dim dFile As String = String.Empty
        Dim ContadorArchivosJPG As Integer = 0
        Dim hashPathArchivosJPG As New Hashtable
        If (Directory.Exists(sourcePath)) Then
            For Each fName As String In Directory.GetFiles(sourcePath)
                dFile = Path.GetExtension(fName)
                If dFile.ToLower.Equals(".jpg") Then
                    ContadorArchivosJPG += 1
                    hashPathArchivosJPG.Add(ContadorArchivosJPG, fName)
                End If
            Next
        End If
        Return hashPathArchivosJPG
    End Function


#End Region


End Class
